package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.qo.PageQo;
import cn.wolfcode.rbac.qo.QueryObject;
import cn.wolfcode.rbac.service.IDepartmentService;
import cn.wolfcode.rbac.web.annotation.RequiredPermission;
import cn.wolfcode.rbac.utils.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//@CrossOrigin(allowCredentials = "true")
@RequestMapping("/api/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    /**
     * 查询所有部门
     * @param qo  当前页数,每页多少条数据
     * @return
     */
    @RequiredPermission(name = "部门分页列表",expression = "department:list")
    @PreAuthorize("hasAuthority('department:list')")
    @GetMapping("list")
    public R query(QueryObject qo){
        PageInfo<Department> pageInfo = departmentService.list(qo);
        PageQo pageQo = new PageQo(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getList(), pageInfo.getTotal());
        return R.ok(pageQo);
    }

    /**
     * 根据id删除指定部门信息
     * @param id
     * @return
     */
    @RequiredPermission(name = "部门删除",expression = "department:delete")
    @PreAuthorize("hasAuthority('department:delete')")
    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable Long id){
        departmentService.delete(id);
        return R.ok("删除成功");
    }

    /**
     * 保存或更新部门信息
     * @param department
     * @return
     */
    @RequiredPermission(name = "部门保存或更新",expression = "department:saveOrUpdate")
    @PreAuthorize("hasAuthority('department:saveOrUpdate')")
    @PostMapping("saveOrUpdate")
    public R saveOrUpdate(@RequestBody Department department){
        if(department.getId() == null){
            departmentService.save(department);
            return R.ok("部门信息保存成功");
        }else{
            departmentService.update(department);
            return R.ok("部门信息更新成功");
        }
    }

    /**
     * 根据id查询指定部门信息
     * @param id
     * @return
     */
    @RequiredPermission(name = "部门信息",expression = "department:info")
    @PreAuthorize("hasAuthority('department:info')")
    @GetMapping("info/{id}")
    public R info(@PathVariable Long id){
        Department department = departmentService.get(id);
        return R.ok("查找成功",department);
    }

    /**
     * 查询所有部门
     * @param
     * @return
     */
    @RequiredPermission(name = "部门列表",expression = "department:listAll")
    @PreAuthorize("hasAuthority('department:listAll')")
    @GetMapping("listAll")
    public R query(){
        List<Department> departments = departmentService.listAll();
        return R.ok(departments);
    }
}
